package com.sixth.health.servict.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sixth.core.entity.*;
import com.sixth.health.mapper.*;
import com.sixth.health.servict.TestResultService;
import com.sixth.health.vo.TestResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class TestResultImpl implements TestResultService {
    @Autowired
    private TestResultMapper testResultMapper;
    @Autowired
    private PatientResultItemMapper patientResultItemMapper;
    @Autowired
    private PatientResultMapper patientResultMapper;

    @Override
    public TestResultVo getTestResult(List<TestDetail> testDetails) {
        // 计算测试结果总和
        int count = testDetails.stream().mapToInt(TestDetail::getHtResult).sum();
        String patientId = testDetails.get(0).getPatientId();
        String htId = testDetails.get(0).getHtId();

        // 查询 TestResult 数据
        QueryWrapper<TestResult> wrapper = new QueryWrapper<>();
        wrapper.eq("ht_id", htId);
        TestResult testResult = testResultMapper.selectOne(wrapper);

        // 创建新测试结果记录
        String prefix = "PR";
        long timestamp = System.currentTimeMillis();
        Random random = new Random();
        int randomNumber = random.nextInt(1000000);
        String prId = prefix + timestamp + String.format("%06d", randomNumber);
        TestResultVo testResultMsg = getTestResultMsg(count, testResult);
        PatientResult patientResult = new PatientResult();
        patientResult.setPrId(prId);
        patientResult.setHtId(htId);
        patientResult.setHtTime(LocalDateTime.now());
        patientResult.setHtResTitle(testResultMsg.getTestResultTitle());
        patientResult.setHtResContent(testResultMsg.getTestResult());
        patientResult.setPatientId(patientId);
        patientResultMapper.insert(patientResult);

        // 插入 PatientResultItem 记录
        for (TestDetail testDetail : testDetails) {
            PatientResultItem patientResultItem = new PatientResultItem();
            String result = getResult(testDetail);
            if (StringUtils.isNotEmpty(result)) {
                patientResultItem.setResult(result);
            }
            patientResultItem.setPrId(prId);
            patientResultItem.setQuestionId(testDetail.getId());
            patientResultItem.setPatientId(patientId);
            patientResultItemMapper.insert(patientResultItem);
        }
        return testResultMsg;
    }

    // 根据结果计数获取测试结果信息
    private TestResultVo getTestResultMsg(Integer count, TestResult testResult) {
        TestResultVo testResultVo = new TestResultVo();
        if (count <= 4) {
            testResultVo.setTestResultTitle(testResult.getATitle());
            testResultVo.setTestResult(testResult.getResA());
        } else if (count <= 10) {
            testResultVo.setTestResultTitle(testResult.getBTitle());
            testResultVo.setTestResult(testResult.getResB());
        } else if (count <= 20) {
            testResultVo.setTestResultTitle(testResult.getCTitle());
            testResultVo.setTestResult(testResult.getResC());
        } else if (count <= 25) {
            testResultVo.setTestResultTitle(testResult.getDTitle());
            testResultVo.setTestResult(testResult.getResD());
        } else if (count <= 30) {
            testResultVo.setTestResultTitle(testResult.getETitle());
            testResultVo.setTestResult(testResult.getResE());
        }
        return testResultVo;
    }

    // 根据 TestDetail 获取结果
    private String getResult(TestDetail testDetail) {
        String htType = testDetail.getHtType();
        Integer htResult = testDetail.getHtResult();
        if ("1".equals(htType)) {
            switch (htResult) {
                case 1: return testDetail.getQuestionA();
                case 2: return testDetail.getQuestionB();
                case 3: return testDetail.getQuestionC();
                case 4: return testDetail.getQuestionD();
                default: return null;
            }
        } else if ("2".equals(htType)) {
            return htResult == 0 ? testDetail.getQuestionN() : testDetail.getQuestionY();
        }
        return null;
    }

    @Override
    public TestResultVo getTestResult02(List<TestDetail> testDetails) {
        String patientId = testDetails.get(0).getPatientId();
        String htId = testDetails.get(0).getHtId();

        // 计算测试结果分类
        String abcd = getABCD(testDetails);

        // 查询 TestResult 数据
        QueryWrapper<TestResult> wrapper = new QueryWrapper<>();
        wrapper.eq("ht_id", htId);
        TestResult testResult = testResultMapper.selectOne(wrapper);

        // 创建新测试结果记录
        String prefix = "PR";
        long timestamp = System.currentTimeMillis();
        Random random = new Random();
        int randomNumber = random.nextInt(1000000);
        String prId = prefix + timestamp + String.format("%06d", randomNumber);
        PatientResult patientResult = new PatientResult();
        patientResult.setPrId(prId);
        patientResult.setHtId(htId);
        patientResult.setHtTime(LocalDateTime.now());
        patientResult.setPatientId(patientId);

        // 设置测试结果标题和内容
        switch (abcd) {
            case "A":
                patientResult.setHtResTitle(testResult.getATitle());
                patientResult.setHtResContent(testResult.getResA());
                break;
            case "B":
                patientResult.setHtResTitle(testResult.getBTitle());
                patientResult.setHtResContent(testResult.getResB());
                break;
            case "C":
                patientResult.setHtResTitle(testResult.getCTitle());
                patientResult.setHtResContent(testResult.getResC());
                break;
            case "D":
                patientResult.setHtResTitle(testResult.getDTitle());
                patientResult.setHtResContent(testResult.getResD());
                break;
        }

        TestResultVo testResultVo = new TestResultVo();
        testResultVo.setTestResultTitle(patientResult.getHtResTitle());
        testResultVo.setTestResult(patientResult.getHtResContent());
        patientResultMapper.insert(patientResult);

        // 插入 PatientResultItem 记录
        for (TestDetail testDetail : testDetails) {
            PatientResultItem patientResultItem = new PatientResultItem();
            String result = getResult(testDetail);
            if (StringUtils.isNotEmpty(result)) {
                patientResultItem.setResult(result);
            }
            patientResultItem.setPrId(prId);
            patientResultItem.setPatientId(patientId);
            patientResultItem.setQuestionId(Integer.valueOf(testDetail.getId()));
            patientResultItemMapper.insert(patientResultItem);
        }
        return testResultVo;
    }

    // 根据测试细节计算分类结果
    private String getABCD(List<TestDetail> testDetails) {
        Map<String, Integer> map = new HashMap<>();
        Map<String, Integer> lastMap = new HashMap<>();
        initializeMap(map);
        initializeMap(lastMap);

        // 计算各分类的得分
        for (int i = 0; i < testDetails.size(); i++) {
            TestDetail testDetail = testDetails.get(i);
            Integer htResult = testDetail.getHtResult();
            if (i < 15) {
                incrementMapValue(map, htResult);
            } else if (i < 30) {
                incrementMapValue(lastMap, htResult);
            }
        }

        // 计算分类得分总和
        int red = map.get("A") + lastMap.get("D");
        int blue = map.get("B") + lastMap.get("C");
        int yellow = map.get("C") + lastMap.get("B");
        int green = map.get("D") + lastMap.get("A");

        // 找到最大得分对应的分类
        int maxValue = Arrays.stream(new int[]{red, blue, yellow, green}).max().orElse(0);
        if (maxValue == red) return "A";
        if (maxValue == blue) return "B";
        if (maxValue == yellow) return "C";
        return "D";
    }

    // 初始化 Map
    private void initializeMap(Map<String, Integer> map) {
        map.put("A", 0);
        map.put("B", 0);
        map.put("C", 0);
        map.put("D", 0);
    }

    // 增加 Map 中指定分类的计数
    private void incrementMapValue(Map<String, Integer> map, Integer htResult) {
        switch (htResult) {
            case 1: map.put("A", map.get("A") + 1); break;
            case 2: map.put("B", map.get("B") + 1); break;
            case 3: map.put("C", map.get("C") + 1); break;
            case 4: map.put("D", map.get("D") + 1); break;
            default: break;
        }
    }
}
